package com.mas.admin.biz.service.auth;

import com.mas.admin.biz.controller.admin.auth.vo.AuthLoginReqVO;
import com.mas.admin.biz.controller.admin.auth.vo.AuthLoginRespVO;
import com.mas.admin.biz.convert.auth.AuthConvert;
import com.mas.admin.biz.convert.auth.OAuth2TokenConvert;
import com.mas.admin.biz.dal.dataobject.oauth2.OAuth2AccessTokenDO;
import com.mas.admin.biz.dal.dataobject.users.AdminUserDO;
import com.mas.admin.biz.service.oauth2.OAuth2TokenService;
import com.mas.admin.biz.service.users.AdminUserService;
import com.mas.admin.enums.logger.LoginLogTypeEnum;
import com.mas.admin.enums.oauth2.OAuth2ClientConstants;
import com.mas.framework.common.enums.UserTypeEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author godyao
 * @description Auth Service 实现类
 * @date 2023年01月28日23:08
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminAuthServiceImpl implements AdminAuthService{

    private final AdminUserService adminUserService;

    private final PasswordEncoder passwordEncoder;

    private final OAuth2TokenService oauth2TokenService;

    private final HttpServletRequest request;

    @Override
    public AdminUserDO authenticate(String username, String password) {
        // 校验账号是否存在
        AdminUserDO user = adminUserService.getUserByUsername(username);
        if (user == null) {
            // TODO 记录日志 并返回异常
            //createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            //throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
            log.error("用户不存在");
        }
        assert user != null;
        if (!passwordEncoder.matches(password, user.getPassword())) {
            // 用户名密码不匹配
            log.error("用户名密码不匹配");
        }
        // TODO 检查是否禁用
        return user;
    }

    @Override
    public AuthLoginRespVO login(AuthLoginReqVO reqVO) {
        // TODO 校验验证码
        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());

        // TODO 如果 socialType 非空，说明需要绑定社交用户
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);

    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除 accessToken
        final OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // TODO 删除成功，则记录登出日志
        //createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    @Override
    public AuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return OAuth2TokenConvert.INSTANCE.convert2(accessTokenDO);
    }

    private AuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // TODO 插入登陆日志
        // createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType().getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 构建返回结果
        return AuthConvert.INSTANCE.convert(accessTokenDO);
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }
}
